let btn = document.getElementById("login-btn");
let inputAccount = document.getElementById("inputID");
let inputPassword = document.getElementById("inputPassword");
let account_msg = document.getElementById("account-msg");
let password_msg = document.getElementById("password-msg");

let id;
let password;
let account_class = inputAccount.getAttribute("class");
let password_class = inputPassword.getAttribute("class");
let account_invalid_class = account_class.concat(" is-invalid");
let password_invalid_class = password_class.concat(" is-invalid");
let account_valid_class = account_class.concat(" is-valid");
let password_valid_class = password_class.concat(" is-valid");

function checkForm() {
  id = inputAccount.value;
  password = inputPassword.value;

  if (id === "") {
    inputAccount.setAttribute("class", account_invalid_class);
    account_msg.innerHTML = "请输入账号";
  } else if (password === "") {
    inputAccount.setAttribute("class", account_valid_class);
    inputPassword.setAttribute("class", password_invalid_class);
    password_msg.innerHTML = "请输入密码";
  } else {
    submit();
  }
}

function focusInput() {
  inputAccount.setAttribute("class", account_class);
  inputPassword.setAttribute("class", password_class);
}

function submit() {
  $.ajax({
    type: "POST",
    url: "http://test.eslans.com:8000/user/login",
    data: {
      id: id,
      password: password,
    },
    success: function (result) {
      if (result.succ) {
        Cookies.set("UID", result.data.uid);
        Cookies.set("nick", result.data.name);
        Cookies.set("image_url", result.data.image_url);
        Cookies.set("gender", result.data.gender);
        Cookies.set("signature", result.data.signature);
        Cookies.set("hidden_Point", result.data.hidden_Point);
        Cookies.set("winNum", result.data.winNumber);
        Cookies.set("loseNum", result.data.loseNumber);
        Cookies.set("drawNum", result.data.drawNumber);
        window.location.href = "main.html";
      } else {
        inputAccount.setAttribute("class", account_invalid_class);
        inputPassword.setAttribute("class", password_invalid_class);
        password_msg.innerHTML = "账号或密码错误";
      }
    },
    error: function (error) {
      console.log(error);
    },
  });
}

btn.onclick = function () {
  checkForm();
};

$("body").keypress(function (event) {
  if (event.which === 13) {
    btn.click();
  }
});
